package com.yiwenup.struct._01_linear.queue;

import java.util.Arrays;

/**
 * 循环双端队列
 **/
@SuppressWarnings("unchecked")
public class CircleDeque<E> {
    private int head;
    private int size;
    private E[] elements;

    public static final int DEFAULT_CAPACITY = 10;

    public CircleDeque() {
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void enQueueHead(E ele) {
        ensureCapacity(size + 1);
        head = index(-1);
        elements[head] = ele;
        size++;
    }

    public void enQueueTail(E ele) {
        ensureCapacity(size + 1);
        elements[index(size)] = ele;
        size++;
    }

    public E deQueueHead() {
        E element = elements[head];
        elements[head] = null;
        head = index(1);
        size++;
        return element;
    }

    public E deQueueTail() {
        int idx = index(size - 1);
        E element = elements[idx];
        elements[idx] = null;
        size--;
        return element;
    }

    public E head() {
        return elements[head];
    }

    public E tail() {
        return elements[index(size - 1)];
    }

    public void clear() {
        for (int i = 0; i < size; i++) {
            elements[index(i)] = null;
        }
        size = 0;
        head = 0;
    }

    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) return;

        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[index(i)];
        }
        elements = newElements;

        head = 0;
    }

    private int index(int idx) {
        idx += head;
        if (idx < 0) {
            return idx + elements.length;
        }
        return idx - (idx >= elements.length ? elements.length : 0);
    }

    @Override
    public String toString() {
        return "CircleDeque{" +
                "head=" + head +
                ", size=" + size +
                ", elements=" + Arrays.toString(elements) +
                '}';
    }
}
